package com.mdinic.blogovi.ctrl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.mdinic.blogovi.model.Person;
import com.mdinic.blogovi.model.ReadShare;
import com.mdinic.blogovi.model.Share;

@RequestMapping("/readshares")
@Controller
@RooWebScaffold(path = "readshares", formBackingObject = ReadShare.class)
@RooWebFinder
public class ReadShareController {

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid ReadShare readShare, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, readShare);
            return "readshares/create";
        }
        uiModel.asMap().clear();
        readShare.persist();
        return "redirect:/readshares/" + encodeUrlPathSegment(readShare.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new ReadShare());
        List<String[]> dependencies = new ArrayList<String[]>();
        if (Person.countPeople() == 0) {
            dependencies.add(new String[] { "person", "people" });
        }
        if (Share.countShares() == 0) {
            dependencies.add(new String[] { "share", "shares" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "readshares/create";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("readshare", ReadShare.findReadShare(id));
        uiModel.addAttribute("itemId", id);
        return "readshares/show";
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("readshares", ReadShare.findReadShareEntries(firstResult, sizeNo));
            float nrOfPages = (float) ReadShare.countReadShares() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
                    : nrOfPages));
        } else {
            uiModel.addAttribute("readshares", ReadShare.findAllReadShares());
        }
        return "readshares/list";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid ReadShare readShare, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, readShare);
            return "readshares/update";
        }
        uiModel.asMap().clear();
        readShare.merge();
        return "redirect:/readshares/" + encodeUrlPathSegment(readShare.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, ReadShare.findReadShare(id));
        return "readshares/update";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        ReadShare readShare = ReadShare.findReadShare(id);
        readShare.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/readshares";
    }

    void populateEditForm(Model uiModel, ReadShare readShare) {
        uiModel.addAttribute("readShare", readShare);
        uiModel.addAttribute("people", Person.findAllPeople());
        uiModel.addAttribute("shares", Share.findAllShares());
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }

    @RequestMapping(params = { "find=ByFollowShare", "form" }, method = RequestMethod.GET)
    public String findReadSharesByFollowShareForm(Model uiModel) {
        uiModel.addAttribute("shares", Share.findAllShares());
        return "readshares/findReadSharesByFollowShare";
    }

    @RequestMapping(params = { "find=ByPerson", "form" }, method = RequestMethod.GET)
    public String findReadSharesByPersonForm(Model uiModel) {
        uiModel.addAttribute("people", Person.findAllPeople());
        return "readshares/findReadSharesByPerson";
    }

    @RequestMapping(params = "find=ByPerson", method = RequestMethod.GET)
    public String findReadSharesByPerson(@RequestParam("person") Person person, Model uiModel) {
        uiModel.addAttribute("readshares", ReadShare.findReadSharesByPerson(person).getResultList());
        return "readshares/list";
    }
}
